package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Role;
import cn.wolfcode.mapper.RoleMapper;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private IPermissionService permissionService;


    //    分页相关
    @Override
    public PageInfo<Role> query(QueryObject qo) {
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Role> roles = roleMapper.getList(qo);
        return new PageInfo(roles);
    }

    @Override
    public Role get(Long id) {
        Role role = roleMapper.selectByPrimaryKey(id);
        return role;
    }

    @Transactional
    @Override
    public void update(Role role, Long[] ids) {
//更新了角色信息名字跟缩写
        roleMapper.updateByPrimaryKey(role);
//将原来的数据删除,再将现在的关系放进关系表
        //删除关系
        roleMapper.deleteRelation(role.getId());
        //新增关系
        if(ids!=null&&ids.length>0) {
            for (Long pId : ids) {
                roleMapper.insertRelation(role.getId(), pId);
            }
        }
    }

    @Transactional
    @Override
    public void save(Role role, Long[] ids) {
//        插入了角色信息名字跟缩写
        roleMapper.insert(role);
        //        将其与权限的关系保存在中间表中
//        遍历获得的id,将他们存在中间表
        if(ids!=null&&ids.length>0) {
            for (Long pId : ids) {
                roleMapper.insertRelation(role.getId(), pId);
            }
        }
    }

    @Override
    public void delete(Long id) {
        roleMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<Role> getList() {

        return   roleMapper.selectAll();
    }

    @Override
    public List<Role> getRole(Long eId) {
        List<Role> roles = roleMapper.selectByeId(eId);
        return roles;
    }


}
